import { Select } from "antd";
import { DefaultOptionType, SelectProps } from "antd/lib/select";
import { debounce } from "lodash";
import { FC, useCallback, useEffect, useRef, useState } from "react";
import { getAdmin } from "src/api";
import { AdminRecord } from "src/views/admin/AdminType";

const UserNameSelect: FC<SelectProps & { optionValueKey?: "username" | "_id"; reflexItem?: (item?: AdminRecord) => void }> = props => {
	const { optionValueKey, reflexItem, onChange, ...restOfProps } = props;
	const userNameListRef = useRef<AdminRecord[]>([]);
	const [usernameOptions, setUsernameOptions] = useState<DefaultOptionType[]>([]);
	const searchUserName = async (value: string) => {
		const query: { username: string } | Record<string, unknown> = {};
		if (value) query.username = { like: true, value };
		const result = await getAdmin(query);
		const { data = [] } = result.data || {};
		setUsernameOptions(data.map(item => ({ label: item.username, value: item[optionValueKey || "username"] })));
		userNameListRef.current = data;
	};
	const searchUserNameDebounce = useCallback(debounce(searchUserName, 300), []);
	const handleChange = (value: unknown, option: DefaultOptionType | DefaultOptionType[]) => {
		onChange?.(value, option);
		reflexItem?.(userNameListRef.current.find(item => item[optionValueKey || "username"] === value));
	};
	useEffect(() => {
		searchUserName("");
	}, []);
	return (
		<Select
			allowClear
			showSearch
			placeholder="输入用户名"
			onSearch={searchUserNameDebounce}
			options={usernameOptions}
			{...restOfProps}
			onChange={handleChange}
		/>
	);
};
UserNameSelect.defaultProps = {
	optionValueKey: "username",
	reflexItem: () => null,
};

export default UserNameSelect;
